package org.raymond.iworks.study.basic.thread.atomicinteger;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo1 {
    public static void main(String[] args) {
        testMapComputeAtomic();
    }

    /**
     *  如果key对应的值不存在,且函数返回的值不为空,则添加一条数据到map,用函数返回的值作为value
     *  如果key对应的值存在,且函数返回的值不为空,则用函数返回的值替换原值
     *  如果key对应的值存在,且函数返回的值为空,则删除key对应的值
     */
    public static void testMapCompute(){
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap();
        map.put("k1", "1");
        map.put("k2", "2");
        map.put("k3", "3");

        map.compute("k1", (k,v)->print(k,v,"1"));
        map.compute("k2", (k,v)->print(k,v,"v2"));
        map.compute("k3", (k,v)->print(k,v,null));
        map.compute("k4", (k,v)->print(k,v,"v4"));
        map.compute("k5", (k,v)->print(k,v,null));
    }
    public static void testMapComputeAtomic(){
        ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap();
        map.put("k1", new AtomicInteger(1));
        map.put("k2", new AtomicInteger(2));
        map.put("k3", new AtomicInteger(3));

        map.compute("k1", (k,v)->print(k,v,new AtomicInteger(1)));
        map.compute("k2", (k,v)->print(k,v,new AtomicInteger(22)));
        map.compute("k3", (k,v)->print(k,v,null));
        map.compute("k4", (k,v)->print(k,v,new AtomicInteger(4)));
        map.compute("k5", (k,v)->print(k,v,null));
    }

    public static String print(String k, String oldv, String newv){
        System.out.printf("(%s,%s)->%s\n", k, oldv, newv);
        return newv;
    }
    public static AtomicInteger print(String k, AtomicInteger oldv, AtomicInteger newv){
        System.out.printf("(%s,%d)->%d\n", k, oldv==null?null:oldv.get(), newv==null?null:newv.get());
        return newv;
    }
}
